package astudy.io;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

import org.apache.commons.io.IOUtils;

public class ZipUtils {

	private ZipUtils() {}
	
	public static void compress(File[] files, File zipfile) 
	throws IOException {
	
		ZipOutputStream os = new ZipOutputStream(
								new BufferedOutputStream(
									new FileOutputStream(zipfile)
								)
							);
		for (File file: files) {
			FileInputStream fis = new FileInputStream(file);
			os.putNextEntry(new ZipEntry(file.getName()));
			IOUtils.copy(fis, os);
			IOUtils.closeQuietly(fis);
		}
		IOUtils.closeQuietly(os);
	}
	
	@SuppressWarnings("unchecked")
	public static void decompress(File zipfile, String folder) 
	throws ZipException, IOException {

		File outputFolder = new File(folder);
		if (!outputFolder.exists()) {
			outputFolder.mkdirs();
		}
		//decompress
		ZipFile zip = new ZipFile(zipfile);
		Enumeration entries = zip.entries();
		while (entries.hasMoreElements()) {
			ZipEntry entry = (ZipEntry)entries.nextElement();
			if (entry.isDirectory()) {
				new File(folder + entry.getName()).mkdirs();
			} else {
				File file = new File(folder + entry.getName());
				File parent = file.getParentFile();
				if (parent != null && !parent.exists()) {
					parent.mkdirs();
				}
				BufferedInputStream bis = new BufferedInputStream(zip.getInputStream(entry));
				FileOutputStream fos = new FileOutputStream(file);
				IOUtils.copy(bis, fos);
				IOUtils.closeQuietly(fos);
				IOUtils.closeQuietly(bis);
			}
		}
		zip.close();
	}
}
